/**
 * @file acwing/95/main.cpp
 * @author Ruiming Guo (guoruiming@stu.scu.edu.cn)
 * @brief 每个灯有一个开关，点一个开关之后，上下左右的灯都会变化
 *
 * 10111
 * 01101
 * 10111
 * 10000
 * 11011
 *
 * 求能否在 6 步之内让灯全亮。
 *
 * 解决方案是：枚举第一行的操作，之后要使得灯全亮，每一行的操作都是唯一确定的
 *
 * 记录最小操作次数 res，如果最终 res <= 6 则成功。
 *
 * @see <https://www.acwing.com/problem/content/97/>
 * @version 1.0
 * @date 2022-05-03
 *
 * @copyright Copyright (c) 2022
 *
 **/

#include <cstdio>
#include <cstring>

using namespace std;

const int N = 6;
char g[N][N], bg[N][N];
const int dx[5] = {-1, 0, 1, 0, 0};
const int dy[5] = {0, 1, 0, -1, 0};
void turn(int x, int y) {
  for (int i = 0; i < 5; ++i) {
    int a = x + dx[i], b = y + dy[i];
    if (a < 0 || a >= 5 || b < 0 || b >= 5) continue;
    g[a][b] ^= 1;
  }
}

int main() {
  int tc;
  scanf("%d", &tc);
  while (tc--) {
    for (int i = 0; i < 5; ++i) scanf("%s", bg[i]);
    int res = 10;
    for (int op = 0; op < 1 << 5; ++op) {
      int cnt = 0;
      memcpy(g, bg, sizeof g);
      // 操作第一行的开关
      for (int i = 0; i < 5; ++i)
        if (op >> i & 1) {
          turn(0, i);
          cnt++;
        }

      // 递推第1~4行开关的状态
      for (int i = 0; i < 4; ++i)
        for (int j = 0; j < 5; ++j) {
          if (g[i][j] == '0') {
            turn(i + 1, j);
            cnt++;
          }
        }

      // 检查最后一行灯是否全亮
      bool success = true;
      for (int i = 0; i < 5; ++i)
        if (g[4][i] == '0') success = false;
      if (success && res > cnt) res = cnt;
    }
    if (res > 6) res = -1;
    printf("%d\n", res);
  }
}
